import React, { ReactElement } from 'react'
import { Upload, Button, message } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { FileSchema } from '@src/components/schema/fileSchema'
import { awaitWrap } from '@js/tool'
import { requestFiles } from '@js/request'
import style from './index.module.less'
import ImgCrop from 'antd-img-crop'
import { download } from '@src/assets/js/downloadRename'

interface Props {
  value?: FileType[]
  onChange?: (v: FileType[]) => void
  accept?: string
  maxLength?: number
  image?: boolean
  placeholder?: string
  aspect?: number
}

interface UploadFile {
  filename: string
  id: string
  url: string
}

function getUploadProps (accept: string | undefined, fileList: FileType[], setFileList: (v: FileType[]) => void): Object {
  const acceptList: string[] = typeof accept === 'string' ? accept.split(',') : []
  const o: { [k: string]: any } = {
    onRemove: (file: FileType) => {
      const index = fileList.indexOf(file)
      const newFileList = fileList.slice()
      newFileList.splice(index, 1)
      setFileList(newFileList)
    },
    beforeUpload: (file: FileType | File) => {
      const lastIndex = file.name.lastIndexOf('.')
      const fType = file.name.slice(lastIndex)
      if (!acceptList.includes(fType)) {
        message.warning(`文件的格式必须为${accept as string}`).then(null, null)
        return false
      }
      const f: FileType = { originFileObj: file as File, name: file.name, filename: file.name, id: '', url: '', original_filename: '', path: '' }
      const l = [...fileList, f]
      setFileList(l)
      return false
    },
    fileList,
    onPreview: (file: FileSchema) => {
      download(file.path, file.original_filename)
      return false
    }
  }
  // if (accept !== undefined) {
  //   o.accept = accept
  // }
  return o
}

async function uploadsRequst (files: File[]): Promise<UploadFile[]> {
  const arr = await requestFiles(files)
  return arr
}

export async function uploadFile (fileList: FileType[]): Promise<FileSchema[]> {
  let uploaded: FileSchema[] = []
  const files: File[] = []
  fileList.forEach(li => {
    if (li instanceof File) {
      files.push(li)
    } else if (li.originFileObj instanceof File) {
      files.push(li.originFileObj)
    } else {
      uploaded.push(li)
    }
  })
  if (files.length > 0) {
    const hide = message.loading('上传中', 120)
    const [e, d] = await awaitWrap(uploadsRequst(files))
    hide()
    if (e !== null) {
      return []
    }
    if (d === null) {
      message.error('数据没有返回').then(null, null)
    } else {
      uploaded = uploaded.concat(d.map((li, i) => {
        const file = files[i]
        return {
          ...li,
          original_filename: file.name,
          path: li.url
        }
      }))
    }
  }
  return uploaded
}

function Main ({ value = [], accept, maxLength, image = false, placeholder, aspect = 1, onChange = () => {} }: Props): ReactElement {
  if (image) {
    return (
      <ImgCrop rotate aspect={aspect}>
        <Upload listType='picture-card' {...getUploadProps(accept, value, onChange)}>
          { typeof maxLength === 'number' && value.length >= maxLength ? '' : <div className={style['upload-icon']}><UploadOutlined /></div> }
        </Upload>
      </ImgCrop>
    )
  }
  const remarks = []
  if (accept !== undefined) {
    remarks.push(`支持扩展名：${accept}`)
  }
  if (placeholder !== undefined) {
    remarks.push(placeholder)
  }
  return (
    <div className={style.container}>
      <Upload {...getUploadProps(accept, value, onChange)}>
        <Button disabled={typeof maxLength === 'number' && value.length >= maxLength}>
          <UploadOutlined /> 上传文件
        </Button>
      </Upload>
      <div className={style.submessage}>{remarks.join('，')}</div>
    </div>
  )
}

export type FileType = FileSchema | File

export default Main
